package net.lulihu.pangolin.headless.client.kit;

import lombok.extern.slf4j.Slf4j;
import net.lulihu.pangolin.headless.common.model.Penetrate;
import net.lulihu.pangolin.headless.common.util.FileKit;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 穿透配置
 * <p>
 * 用来记录应用关闭启动时使用同一个映射id 这样不会改变服务端的映射端口
 */
@Slf4j
public class PenetrateConfigKit {

    /**
     * 穿透地址
     */
    private final static String penetratePath;

    static {
        String tmpdir = System.getProperty("java.io.tmpdir");
        tmpdir = tmpdir.endsWith(File.separator) ? tmpdir : tmpdir + File.separator;
        penetratePath = tmpdir + "pangolin" + File.separator + "penetrate.txt";
    }

    /**
     * 读取配置 并且转换为Map
     *
     * @return 按行读
     */
    public static Map<String, String> readToMap() {
        List<String> lines = read();
        Map<String, String> addressMappingId = new HashMap<>();
        if (lines != null && lines.size() > 0) {
            for (String line : lines) {
                String[] split = line.split("-");
                addressMappingId.put(split[0], split[1]);
            }
        }
        return addressMappingId;
    }

    /**
     * 读取配置
     *
     * @return 按行读
     */
    public static List<String> read() {
        try {
            return FileKit.readFileAccordingToLine(penetratePath);
        } catch (IOException e) {
            log.error("穿透结果配置读取文件失败", e);
        }
        return null;
    }

    /**
     * 写入配置
     *
     * @param penetrates 穿透信息
     */
    public static void write(List<Penetrate> penetrates) {
        List<String> penetrateConfig = new ArrayList<>(penetrates.size());

        for (Penetrate penetrate : penetrates) {
            String mappingId = penetrate.getMappingId();
            if (mappingId != null)
                penetrateConfig.add(penetrate.getAddress() + "-" + mappingId);
        }

        try {
            FileKit.writeFile(penetratePath, penetrateConfig);
        } catch (IOException e) {
            log.error("穿透结果配置写入文件失败", e);
        }
    }


}
